<template>
	<view v-if="isShow" class="page group-invite">

		<nav-header title="选择用户" :auto-back="true">
			<template v-slot:left>
				<view class="left">
					<slot name="left">
						<uni-icons class="back" type="back" :color="leftIconColor" size="28"
							@tap="onNavBack()"></uni-icons>
					</slot>
				</view>
			</template>
			<template v-slot:right>
				<view class="confirm-text" :disabled="inviteSize == 0" @click="onInviteFriends()">确认</view>
			</template>
		</nav-header>

		<view class="search-bar">
			<uni-search-bar v-model="searchText" radius="100" cancelButton="none"
				placeholder="输入好友昵称搜索"></uni-search-bar>
		</view>

		<view class="friend-items">
			<up-index-list :index-list="friendIdx">
				<template v-for="(friends, i) in friendGroups">
					<up-index-item>
						<up-index-anchor :text="friendIdx[i] == '*' ? '在线' : friendIdx[i]"
							bgColor="#f2f3fd"></up-index-anchor>
						<view v-for="friend in friends" v-show="!searchText || friend.nickName.includes(searchText)"
							:key="friend.id">
							<view class="friend-item" @tap.stop.native="onSwitchChecked(friend)">
								<!-- 单选 -->
								<view v-if="!isMultipleSelectable" class="friend-checked">
									<radio style="transform:scale(0.8)" :checked="friend === currentSelectedFriend"
										:disabled="friend.disabled" @tap.stop.native="onSwitchChecked(friend)" />
								</view>
								<!-- 多选 -->
								<view v-else class="friend-checked">
									<radio style="transform:scale(0.8)" :checked="friend.checked"
										:disabled="friend.disabled" @tap.stop.native="onSwitchCheckeds(friend)" />
								</view>
								<view @tap.stop.native="onSwitchCheckeds(friend)" >
									<head-image :name="friend.nickName" :online="friend.online" :url="friend.headImage"
										:size="90"></head-image>
								</view>
								<view class="friend-name" @tap.stop.native="onSwitchCheckeds(friend)">
									{{ userStore.userInfo.id == friend.id && '我' || friend.nickName }}
								</view>
							</view>
						</view>
					</up-index-item>
				</template>
			</up-index-list>
		</view>

	</view>
</template>

<script>
	import {
		pinyin
	} from 'pinyin-pro';
	export default {
		name: 'SelectUser', // 定义组件名称，方便在其他地方引用
		props: {
			// 可以在这里定义组件接收的外部属性，例如如果groupId需要从外部传入，可如下定义
			groupId: {
				type: [Number, String], // 根据实际情况确定类型，这里假设可能是数字或者字符串类型的群组ID
				required: true // 如果这个属性是必须传入的，设置为true
			},
			url: {
				type: [String],
			},
			method: {
				type: [String]
			},
			isShow: {
				type: [Boolean],
				default: false
			},
			isMultipleSelectable: {
				type: [Boolean],
				default: false
			},


		},
		data() {
			return {
				currentSelectedFriend: null,
				searchText: "",
				groupMembers: [],
				friendItems: [],
			}
		},
		methods: {
			// 绑定用户
			onInviteFriends() {
				console.log("测试绑定用户")
				// 通过 $emit 触发自定义事件，将选择的用户数据回传给父组件
				this.$emit('userSelected', this.friendItems.filter(f => f.checked));

			},
			// 导航到用户信息页面
			onShowUserInfo(userId) {
				uni.navigateTo({
					url: "/pageSubOne/common/user-info?id=" + userId
				})
			},
			onNavBack() {
				try {
					// 通过 $emit 触发自定义事件，将选择的用户数据回传给父组件
					this.$emit('onShow');
				} catch (error) {
					console.error('触发 onShow 事件时出现错误：', error);
				}
			},
			// 单选
			onSwitchChecked(friend) {
				if (!friend.disabled) {
					// 将当前点击的好友设置为选中状态
					this.currentSelectedFriend = friend;
					friend.checked = true
					// 遍历所有好友，将除了当前选中的好友之外的其他好友的选中状态都设为false
					this.friendItems.forEach(f => {
						if (f !== friend) {
							f.checked = false;
						}
					});
				}
			},
			// 多选
			onSwitchCheckeds(friend) {
				if (!friend.disabled) {
					friend.checked = !friend.checked;
				}
			},
			// 初始化好友列表
			initFriendItems() {
				this.friendItems = [];
				let friends = this.groupMembers
				friends.forEach((f => {
					let item = {
						id: f.id,
						headImage: f.headImage,
						nickName: f.nickName,
						online: f.online
					}
					item.disabled = false
					item.checked = false
					this.friendItems.push(item);
				}))
			},
			// 加载群组成员
			loadGroupMembers() {
				this.$http({
					url: `${this.url}`,
					method: this.method
				}).then((members) => {
					this.groupMembers = members.filter(m => !m.quit);
					console.log("this.groupMembers", this.groupMembers)
					this.initFriendItems();
				})
			},
			// 检查给定的用户ID是否在群组成员列表中


			firstLetter(strText) {
				// 使用pinyin-pro库将中文转换为拼音
				let pinyinOptions = {
					toneType: 'none',
					type: 'normal'
				};
				let pyText = pinyin(strText, pinyinOptions);
				return pyText[0];
			},
			isEnglish(character) {
				return /^[A-Za-z]+$/.test(character);
			}
		},
		computed: {
			inviteSize() {
				return this.friendItems.filter(f => !f.disabled && f.checked).length;
			},

			friendGroupMap() {
				// 按首字母分组
				let groupMap = new Map();
				this.friendItems.forEach((f) => {
					if (this.searchText && !f.nickName.includes(this.searchText)) {
						return;
					}
					let letter = this.firstLetter(f.nickName).toUpperCase();
					// 非英文一律为#组
					if (!this.isEnglish(letter)) {
						letter = "#"
					}
					if (f.online) {
						letter = '*'
					}
					if (groupMap.has(letter)) {
						groupMap.get(letter).push(f);
					} else {
						groupMap.set(letter, [f]);
					}
				})
				// 排序
				let arrayObj = Array.from(groupMap);
				arrayObj.sort((a, b) => {
					// #组在最后面
					if (a[0] == '#' || b[0] == '#') {
						return b[0].localeCompare(a[0])
					}
					return a[0].localeCompare(b[0])
				})
				groupMap = new Map(arrayObj.map(i => [i[0], i[1]]));
				return groupMap;
			},
			friendIdx() {
				return Array.from(this.friendGroupMap.keys());
			},
			friendGroups() {
				return Array.from(this.friendGroupMap.values());
			}
		},
		created() {
			// 进入页面加载这个数据
			this.loadGroupMembers();
		}
	}
</script>
<style lang="scss" scoped>
	.group-invite {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;

		.confirm-text {
			font-size: 30rpx;
			color: #1989FA;
		}

		.friend-items {
			position: relative;
			flex: 1;
			overflow: hidden;

			.friend-item {
				height: 120rpx;
				display: flex;
				margin-bottom: 1rpx;
				position: relative;
				padding: 0 30rpx;
				align-items: center;
				background-color: white;
				white-space: nowrap;

				.friend-checked {
					margin-right: 20rpx;
				}

				.friend-name {
					flex: 1;
					padding-left: 20rpx;
					font-size: 30rpx;
					font-weight: 600;
					line-height: 60rpx;
					white-space: nowrap;
					overflow: hidden;
				}
			}

			.scroll-bar {
				height: 100%;
			}
		}
	}
</style>